
$(function() {

	width = 960;
	height = 480;

	var xy = d3.geo.mercator().translate([461, 206]).scale(1000),//.scale(870),
		path = d3.geo.path().projection(xy),
		total = 0;

	var vis = d3.select("#chart").append("svg:svg");


	map = vis.append("svg:g")
		.attr("id", "states")
		.attr("transform","translate(0,100)");
		//.call(zoom);

	var map_zoom = d3.behavior.zoom()
			.translate([0,100])
		//.scale(xy.scale())
			.scaleExtent([1, 5]);
	//.on("zoom", redraw);

	zoom_scale = 1;



	d3.json("world-countries.json", function(collection) {

		d3.select("#states")
			.selectAll("path")
			.data(collection.features)
			.enter().append("svg:path")
			.attr("d", path);

		d3.json("sumbyyear_constant_dollar.json", function(json) {

		d3.json("events_final_3_separate3.json", function(events_json) {
			function getnews(year_index){
				console.log("get news year index:"+year_index);

				var thisyear=events_json[year_index];
				if (thisyear==undefined) {
					return ("year "+ (startYear+year_index) +" has no news");
				} else {
					var returnstr='';
					//var pair;
					for (var i=0; i< thisyear.news.length; i++) {
						returnstr=returnstr+'<div id="newscountry">'+thisyear.news[i].country_name+
						'</div><div id="newsevents"><a href="https://www.google.com/search?pz=1&cf=all&ned=us&hl=en&tbm=nws&gl=us&as_epq='+thisyear.news[i].event1+'" target="_blank">'+thisyear.news[i].event1+"</a></div>"+
						'<div id="newsevents"><a href="https://www.google.com/search?pz=1&cf=all&ned=us&hl=en&tbm=nws&gl=us&as_epq='+thisyear.news[i].event2+'" target="_blank">'+thisyear.news[i].event2+"</a></div>"+
						'<div id="newsevents"><a href="https://www.google.com/search?pz=1&cf=all&ned=us&hl=en&tbm=nws&gl=us&as_epq='+thisyear.news[i].event3+'" target="_blank">'+thisyear.news[i].event3+"</a></div>"								
						;

					}
					//returnstr=returnstr+'</div>';

					return (returnstr);
				}


			}


			wDay = 3,
			cDay = 0,
			row = 1,
			dotX = 30,
			dotY = 30,
			leftMargin = 40,
			topMargin = 10;

			var years = [],
			startYear = 1960,
			endYear = 2010,
			yearIndex = 0;


			for(i=startYear; i<endYear+1; i++){
				years.push(i);
			}


			function data(year){
				//console.log("data year:"+year);
				var data = [];
				for(j = 0; j < json.length ; j++) {
					sum = json[j].sums[year-startYear];
					//sum = json[j].sum[0];

					if (sum != 0) {
						data.push(json[j]);
					}
				}
				//console.log("data.length "+data.length);
				return data;
			}

			function showsum(year) {
					var subset = [];
					var names=[];


					for(j=0;j<json.length;j++) {
						sum = json[j].sums[year-startYear];
						name = json[j].country_name;
						subset.push(sum);
						names.push(name);
					}

					insersort(subset,names);

					subset.reverse();
					//names.reverse();
					var topfivesums = [];
					for (i=0;i<5;i++) {

						topfivesums.push(subset[i]);
					}

					return topfivesums;

			}

			
			function insersort(subset,names) {

				for (i=1;i<subset.length+1;i++){
					var current_position = i-1;

					while (current_position!=-1) {
						var current_value=subset[current_position];
						var next_value=subset[current_position+1];
						if (current_value > next_value) {
							swap(current_position,current_position+1,subset);
							swap(current_position,current_position+1,names);
							current_position=current_position-1;
						} else {
							break;
						}
					}
				}



			}

			function swap(valuea,valueb,s) {

				var temp = s[valuea];
				s[valuea]=s[valueb];
				s[valueb]=temp;

			}

			$(document).ready(function() {
				$("#slider").slider({
					min:startYear,
					max: endYear,
					step: 1,
					value: startYear,
					slide: function(event, ui) {
						year = ui.value;
						yearIndex = ui.value - startYear;
						update();
						//vis.render();//new added
					}

				});

			});

			

			d3.select('#play').on('click', playClick);
			//d3.select('#first').on('click', firstClick);
			d3.select('#prev').on('click', prevClick);
			d3.select('#next').on('click', nextClick);
			//d3.select('#last').on('click', lastClick);

			d3.select('#zoom-reset').on('click', zoom_reset);
			d3.select('#zoom-in').on('click', zoom_in);
			d3.select('#zoom-out').on('click', zoom_out);
			
			d3.select('#left_corner').on('click', firstClick);
			d3.select('#right_corner').on('click', lastClick);
			jQuery("#contactFormContainer .contact").click(function(){contact()});
			//only need force for IE6  
			jQuery("#backgroundPopup").css({  
				"height": document.documentElement.clientHeight 
			});  
			var timer=undefined;
			function playClick() {
				//year = yearIndex+startYear;
				if (timer) {
					stop();
				} else {
				
					console.log("timer: yearIndex: "+yearIndex); //starts at 50???
					if ( yearIndex == 50) {
						console.log("timer: reset index to 0");
						
						yearIndex = 0;
						$("#slider").slider('value',startYear+yearIndex);
					}
					

					$("#play").attr("src",'images/pause.png');
					update();
					//vis.render();
					timer = setInterval(function() {
						yearIndex++;
						if (yearIndex >= 50) {
							stop();
						}
						$("#slider").slider('value', startYear+yearIndex);
						update();
						//vis.render();
					}, 900);//900
				}

			} 

			function stop() {
				clearInterval(timer);
				timer = undefined;
				$("#play").attr("src",'images/play.png');
			}

			function firstClick(){
				yearIndex = 0;
				$("#slider").slider('value', startYear+yearIndex);
				update();
			}

			function prevClick(){
				yearIndex = Math.max(0, yearIndex-1);
				$("#slider").slider('value', startYear+yearIndex);
				update();
			}

			function nextClick(){
				yearIndex = Math.min(50, yearIndex+1);
				$("#slider").slider('value', startYear+yearIndex);
				update();
			}

			function lastClick(){
				yearIndex = 50;
				$("#slider").slider('value', startYear+yearIndex);
				update();
			}

			function zoom_reset(){
				console.log('zoom_reset');

				map_zoom.scale(1);
				map_zoom.translate([0,100]);
				map.attr("transform"," scale(1)");
				map.attr("transform","translate(" + [0, 100] + ")");
				zoom_scale = 1;
				update();
			}

			function zoom_in(){
				var p = [480,240], l = location(p, map_zoom.translate(), map_zoom.scale());
				//console.log(p);
				//console.log(l);
				scale = Math.min(map_zoom.scale()*2, 5);

				translate = translateTo(p, l, map_zoom.translate());



				map.attr("transform","translate(" + translate + ")"
						+ " scale(" + scale + ")");

				map_zoom.scale(scale);
				map_zoom.translate(translate);
				console.log(map_zoom.scale()+", "+map_zoom.translate());
				zoom_scale = scale;
				update();
			}

			function zoom_out(){
				var p = [480,240], l = location(p, map_zoom.translate(), map_zoom.scale());
				//console.log(p);
				//console.log(l);
				scale = Math.max(map_zoom.scale()/2, 1);

				translate = translateTo(p, l, map_zoom.translate());
				map.attr("transform","translate(" + translate + ")"
						+ " scale(" + scale + ")");
				//map.attr("transform"," scale("+map_zoom.scale()*2+")");
				map_zoom.scale(scale);
				map_zoom.translate(translate);
				console.log(map_zoom.scale()+", "+map_zoom.translate());
				zoom_scale = scale;
				update();
			}

			function location(p, translate, scale) {
				return [(p[0] - translate[0]) / scale, (p[1] - translate[1]) / scale];
			}

			function point(l, translate) {
				return [l[0] * scale + translate[0], l[1] * scale + translate[1]];
			}

			function translateTo(p, l, translate) {
				l = point(l, translate);
				translate[0] += p[0] - l[0];
				translate[1] += p[1] - l[1];
				return translate;
			}

			lastx = 0;

			//zoom = vis.call(d3.behavior.zoom().on("zoom",redraw));
			//vis.call(d3.behavior.zoom().on("zoom",redraw));
			//vis.call(zoom);
			map_zoom.on('zoom', redraw);
			vis.call(map_zoom);


			update();

			function redraw() {
				console.log("here",d3.event.translate, d3.event.scale);
				zoom_scale = d3.event.scale;

				map.attr("transform","translate(" + d3.event.translate + ")"
					+ " scale(" + zoom_scale + ")");

				update();
			}

			//console.log("scale: "+xy.scale());

			function radius(sum) {
				//return Math.sqrt(x)*.25

				var circle_scale = 0.0005;
				//console.log(Math.sqrt(Math.sqrt(sum))*circle_scale);
				return 3+Math.sqrt(sum)*circle_scale/Math.sqrt(zoom_scale);

			}

			function update() {
				console.log("update:");

				vis.selectAll(".gdots")
				.data(data(years[yearIndex]), function(d) { return d.country_name;})
				.exit()
				.remove();

				vis.selectAll(".dots")
				.transition()
				.attr("r",0)
				.duration(0)
				.remove();

				dotsEnter = map.selectAll("dots")
				.data(data(years[yearIndex]), function(d) { return d.country_name ;})
				.enter().append("svg:g")
				.attr("class", "gdots")

				.attr("transform", function(d) {
					var cord = [d.Lon, d.Lat];
					return "translate(" + xy(cord).join(",") + ")";
				});



				dotsEnter.append("svg:circle")
				.attr("stroke-width", "2")
//						.attr("fill", function(d) {
//							if (d.sums[yearIndex] >= showsum(yearIndex+startYear)[4]) {
//								return "gold";
//							} else {
//								return "green";
//							}
//						})
				.attr("fill", "green")
				.attr("stroke", function(d) {
					if (d.sums[yearIndex] >= showsum(yearIndex+startYear)[4]) {
						return "darkgreen";
					} else {
						return "none";
					}
				})
				.attr("r", 0)
				.attr("class", "dots")
				.attr("fill-opacity", .5) //.5
				.transition()
				.duration(0)
				//.attr("r", function(d) {
				//console.log("draw circle country = "+d.country_name +" r = "+ d.sums[yearIndex]);
				//return Math.sqrt(Math.sqrt(d.sums[yearIndex]))*circle_scale;})
				.attr("r", function(d) {
					return radius(d.sums[yearIndex]);
				})
				.attr("fill-opacity", .5);//.2

				vis.selectAll("circle")
				.on("mouseover",fade(.7))
				.on("mouseout",fade(.5));


				$("#ylabel").html(yearIndex+startYear);
				$("#totalbyyear").html("$"+byYear[yearIndex].toMoney());
				$("#events").html(getnews(yearIndex));




			  //tool tip
			  $('svg circle').tipsy({
				gravity: 'w',
				html: true,
				title: function() {
				  var d = this.__data__;

				  return ""+d.country_name+": $"+d.sums[yearIndex].toMoney();
				}
			  });
			  console.log("end of update: yearIndex: "+yearIndex);

			  console.log("update ends");


			//update the opacity of a circle
			   function fade(opacity) {
				   return function(g, i) {

					 var circle = d3.select(this);
					 if (circle != undefined) {
						circle.attr("fill-opacity", opacity);
					}
				   };
				}

				

				
			}//end update()

		function contact() {
			
		if (jQuery("#contactForm").is(":hidden")){
			jQuery("#contactForm").slideDown("slow");//slideDown
			jQuery("#backgroundPopup").css({"opacity": "0.7"});
			jQuery("#backgroundPopup").fadeIn("slow"); 

		}
		else{
			jQuery("#contactForm").slideUp("slow");//slideUp
			jQuery("#backgroundPopup").fadeOut("slow");  
		}

		
		}
			



			
			});//end events.json d3
		}); //end sumbyyear2.json d3

	});

});